package org.mcb.zebra.portal.context;

import java.io.IOException;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.pluto.PortletContainer;
import org.apache.pluto.PortletContainerException;
import org.apache.pluto.PortletContainerFactory;
import org.mcb.zebra.portal.manager.PortalManager;
import org.mcb.zebra.portal.manager.ZebPortalManager;
import org.mcb.zebra.portal.resource.ResourceConfig;
import org.mcb.zebra.portal.resource.ResourceConfigReader;
import org.mcb.zebra.portal.resource.ZebResourceConfigReader;
import org.mcb.zebra.portal.services.ZebContainerServices;
import org.mcb.zebra.portal.services.ZebPortalCallbackService;
import org.mcb.zebra.portal.url.ZebUrlParser;
import org.xml.sax.SAXException;

public class ZebStartupService implements ServletContextListener{

	@Override
	public void contextDestroyed(ServletContextEvent contextEvent) {
		PortletContainer container =(PortletContainer)contextEvent.getServletContext().getAttribute(PortalManager.PORTLET_CONTAINER);
		if(container!=null){
			try {
				container.destroy();
			} catch (PortletContainerException e) {
				e.printStackTrace();
			}
			contextEvent.getServletContext().removeAttribute(PortalManager.PORTLET_CONTAINER);
		}
		
	}

	@Override
	public void contextInitialized(ServletContextEvent contextEvent) {
		ResourceConfigReader configReader = new ZebResourceConfigReader();
		ResourceConfig config =null;
		try {
			configReader.init();
			config  =configReader.getConfig(contextEvent.getServletContext());
			PortalManager manager  = ZebPortalManager.getInstance();
			manager.setConfig(config);
			manager.setPortalContext(new ZebPortalContext(config));
			manager.setCallbackService(new ZebPortalCallbackService());
			ZebUrlParser parser = new ZebUrlParser();
			manager.setUrlParser(parser);
			PortletContainerFactory factory = PortletContainerFactory.getInstance();
			PortletContainer container = factory.createContainer("test",
					 new ZebContainerServices(), new ZebContainerServices());
			contextEvent.getServletContext().setAttribute(PortalManager.PORTLET_CONTAINER, container);
			contextEvent.getServletContext().setAttribute(PortalManager.PORTAL_MANAGER, manager);
			try {
				container.init(contextEvent.getServletContext());
			} catch (PortletContainerException e) {
				e.printStackTrace();
			}
		} catch (IOException e1) {
			e1.printStackTrace();
		} catch (SAXException e1) {
			e1.printStackTrace();
		}
		
	}

}
